package member.api.vo;

import utils.Lang;
import utils.sql.GenericSpecification;

import javax.persistence.criteria.*;

/**
 * Created by Liang Wenxu on 2017-03-14.
 */
public class MemberInvoiceQuerySpec extends GenericSpecification {

    public MemberInvoiceQuerySpec(MemberInvoiceQueryVo example) {
        super(example);
    }

    @Override
    protected void customPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        MemberInvoiceQueryVo queryVo = (MemberInvoiceQueryVo) super.example;
        if(!(Lang.isEmpty(queryVo.getDateCreatedStart())) && Lang.isEmpty(queryVo.getDateCreatedStart())) {
            Expression expStart = cb.greaterThanOrEqualTo(root.get("dateCreated"), queryVo.getDateCreatedStart());
            Expression expEnd = cb.greaterThanOrEqualTo(root.get("dateCreated"), queryVo.getDateCreatedEnd());
            Expression expCombimed = null;
            if(!(Lang.isEmpty(queryVo.getDateCreatedStart())) && !(Lang.isEmpty(queryVo.getDateCreatedEnd()))) {
                expCombimed = cb.and(expStart,expEnd);
            } else {
                if(!(Lang.isEmpty(queryVo.getDateCreatedStart()))) {
                    expCombimed = expStart;
                }
                if(!(Lang.isEmpty(queryVo.getDateCreatedEnd()))) {
                    expCombimed = expEnd;
                }
            }

            super.addExpression("dateCreated", expCombimed);

        }

        if(Lang.isEmpty(queryVo.getIds())) {
            CriteriaBuilder.In<Object> inExp = cb.in(root.get("id"));
            for(String id : queryVo.getIds()) {
                inExp.value(id);
            }
            super.addExpression("id", inExp);
        }
    }
}
